using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Navigation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Provider;
using Windows.System;

namespace App1
{
    /// <summary>
    /// 文件共享页面
    /// </summary>
    public sealed partial class FileSharePage : Page
    {
        private ObservableCollection<FileShareItem> _fileItems = new ObservableCollection<FileShareItem>();
        private string _currentPath = string.Empty;
        private List<string> _navigationHistory = new List<string>();
        private FileShareHelper _fileShareHelper = new FileShareHelper();
        private List<IPEndPoint> _discoveredServices = new List<IPEndPoint>();
        private IPEndPoint _selectedService;

        public FileSharePage()
        {
            this.InitializeComponent();
            FileListView.ItemsSource = _fileItems;
            _fileShareHelper.FileShared += OnFileShared;
            LoadSharedFiles();
        }

        /// <summary>
        /// 加载共享文件
        /// </summary>
        private async void LoadSharedFiles()
        {
            // 发现局域网中的文件共享服务
            _discoveredServices = await _fileShareHelper.DiscoverFileShareServicesAsync();

            if (_discoveredServices.Count > 0)
            {
                // 选择第一个发现的服务
                _selectedService = _discoveredServices[0];
                await LoadRemoteFiles(_selectedService);
            }
            else
            {
                _fileItems.Clear();
                // 显示未发现服务提示
                EmptyStatePanel.Visibility = Visibility.Visible;
                FileListView.Visibility = Visibility.Collapsed;
            }

            // 更新当前路径显示
            CurrentPathTextBlock.Text = "共享文件"; 

            // 检查是否为空状态
            UpdateEmptyState();
        }

        /// <summary>
        /// 从远程服务加载文件列表
        /// </summary>
        private async Task LoadRemoteFiles(IPEndPoint endPoint)
        {
            try
            {
                _fileItems.Clear();
                var remoteFiles = await _fileShareHelper.GetRemoteFileListAsync(endPoint);

                foreach (var file in remoteFiles)
                {
                    _fileItems.Add(file);
                }

                UpdateEmptyState();
            }
            catch (Exception ex)
            {
                _fileItems.Clear();
                _fileItems.Add(new FileItem
                {
                    Name = "加载失败: " + ex.Message,
                    Path = "",
                    Size = "",
                    Icon = "",
                    IsFolder = false
                });
            }
        }

        /// <summary>
        /// 处理文件共享事件
        /// </summary>
        private void OnFileShared(object sender, FileShareEventArgs e)
        {
            // 当本地文件共享时更新UI
            DispatcherQueue.TryEnqueue(() =>
            {
                _fileItems.Clear();
                foreach (var file in e.Files)
                {
                    _fileItems.Add(file);
                }
                UpdateEmptyState();
            });
        }

        /// <summary>
        /// 获取文件图标
        /// </summary>
        private string GetFileIcon(FileShareType fileType)
        {
            switch (fileType)
            {
                case FileShareType.Video:
                    return "";
                case FileShareType.Audio:
                    return "";
                case FileShareType.Image:
                    return "";
                default:
                    return "";
            }
        }

        /// <summary>
        /// 格式化文件大小
        /// </summary>
        private string FormatFileSize(long sizeInBytes)
        {
            if (sizeInBytes < 1024)
                return $"{sizeInBytes} B";
            else if (sizeInBytes < 1024 * 1024)
                return $"{(sizeInBytes / 1024.0):F2} KB";
            else if (sizeInBytes < 1024 * 1024 * 1024)
                return $"{(sizeInBytes / (1024.0 * 1024.0)):F2} MB";
            else
                return $"{(sizeInBytes / (1024.0 * 1024.0 * 1024.0)):F2} GB";
        }

        /// <summary>
        /// 更新空状态显示
        /// </summary>
        private void UpdateEmptyState()
        {
            EmptyStatePanel.Visibility = _fileItems.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
            FileListView.Visibility = _fileItems.Count == 0 ? Visibility.Collapsed : Visibility.Visible;
        }

        /// <summary>
        /// 返回按钮点击事件
        /// </summary>
        private void BackButton_Click(object sender, RoutedEventArgs e)
        {
            // 这里实现返回上一级文件夹的逻辑
            if (_navigationHistory.Count > 0)
            {
                // 移除最后一个路径
                _navigationHistory.RemoveAt(_navigationHistory.Count - 1);

                // 如果历史记录为空，则加载根目录
                if (_navigationHistory.Count == 0)
                {
                    LoadSharedFiles();
                }
                else
                {
                    // 否则加载上一级目录
                    _currentPath = _navigationHistory.Last();
                    // 这里应该加载指定路径的文件
                    // LoadFilesInPath(_currentPath);
                }
            }
        }

        /// <summary>
        /// 共享文件按钮点击事件
        /// </summary>
        private async void ShareFileButton_Click(object sender, RoutedEventArgs e)
        {
            var filePicker = new FileOpenPicker();
            // 获取当前窗口的HWND
            var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(App.Current._window);
            // 设置文件选择器的所有者窗口
            WinRT.Interop.InitializeWithWindow.Initialize(filePicker, hWnd);

            filePicker.ViewMode = PickerViewMode.Thumbnail;
            filePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            filePicker.FileTypeFilter.Add("*");

            var file = await filePicker.PickSingleFileAsync();
            if (file != null)
            {
                // 这里实现文件共享逻辑
                // 为了演示，我们只是添加到列表中
                var fileProperties = await file.GetBasicPropertiesAsync();
                var fileItem = new FileShareItem
                {
                    Name = file.Name,
                    Path = file.Path,
                    Size = fileProperties.Size,
                    Type = GetFileShareType(file.FileType)
                };
                _fileItems.Add(fileItem);
                UpdateEmptyState();

                // 启动文件共享
                await _fileShareHelper.StartSharingAsync(Path.GetDirectoryName(file.Path));
            }
        }

        /// <summary>
        /// 共享文件夹按钮点击事件
        /// </summary>
        private async void ShareFolderButton_Click(object sender, RoutedEventArgs e)
        {
            var folderPicker = new FolderPicker();
            // 获取当前窗口的HWND
            var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(App.Current._window);
            // 设置文件夹选择器的所有者窗口
            WinRT.Interop.InitializeWithWindow.Initialize(folderPicker, hWnd);

            folderPicker.ViewMode = PickerViewMode.Thumbnail;
            folderPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            folderPicker.FileTypeFilter.Add("*");

            var folder = await folderPicker.PickSingleFolderAsync();
            if (folder != null)
            {
                // 启动文件夹共享
                await _fileShareHelper.StartSharingAsync(folder.Path);

                // 更新UI
                var folderItem = new FileShareItem
                {
                    Name = folder.Name,
                    Path = folder.Path,
                    Size = 0,
                    Type = FileShareType.Other
                };
                _fileItems.Add(folderItem);
                UpdateEmptyState();
            }
        }

        /// <summary>
        /// 根据扩展名获取文件类型
        /// </summary>
        /// <param name="fileExtension">文件扩展名</param>
        /// <returns>文件类型</returns>
        private FileShareType GetFileShareType(string fileExtension)
        {
            switch (fileExtension.ToLower())
            {
                case ".mp4":
                case ".avi":
                case ".mkv":
                case ".mov":
                    return FileShareType.Video;
                case ".mp3":
                case ".wav":
                case ".flac":
                case ".aac":
                    return FileShareType.Audio;
                case ".jpg":
                case ".jpeg":
                case ".png":
                case ".gif":
                    return FileShareType.Image;
                default:
                    return FileShareType.Other;
            }
        }

        /// <summary>
        /// 文件列表项点击事件
        /// </summary>
        private void FileListView_ItemClick(object sender, ItemClickEventArgs e)
        {
            var fileItem = e.ClickedItem as FileShareItem;
            if (fileItem != null && _selectedService != null)
            {
                if (fileItem.IsFolder)
                {
                    // 如果是文件夹，则浏览文件夹内容
                    _navigationHistory.Add(_currentPath);
                    _currentPath = fileItem.Path;
                    // 这里应该加载文件夹内容
                    // LoadFilesInPath(_currentPath);
                }
                else
                {
                    // 如果是文件，则预览文件
                    PreviewFile(fileItem);
                }
            }
        }

        /// <summary>
        /// 预览文件
        /// </summary>
        private async void PreviewFile(FileShareItem fileItem)
        {
            // 根据文件类型决定如何预览
            var extension = Path.GetExtension(fileItem.Name).ToLower();

            // 创建临时文件夹
            var tempFolder = Path.Combine(Path.GetTempPath(), "FileSharePreview");
            Directory.CreateDirectory(tempFolder);

            var tempFilePath = Path.Combine(tempFolder, fileItem.Name);

            // 创建进度报告
            var progress = new Progress<double>(percentage =>
            {
                // 可以添加进度条更新逻辑
            });

            try
            {
                // 先下载文件
                await _fileShareHelper.DownloadFileAsync(_selectedService, fileItem.Path, tempFilePath, progress);

                // 预览文件
                if (IsVideoFile(extension))
                {
                    var videoPlayerWindow = new VideoPlayerWindow();
                    videoPlayerWindow.SetVideoSource(tempFilePath);
                    videoPlayerWindow.Activate();
                }
                else if (IsAudioFile(extension))
                {
                    var audioPlayerWindow = new AudioPlayerWindow();
                    audioPlayerWindow.SetAudioSource(tempFilePath);
                    audioPlayerWindow.Activate();
                }
                else
                {
                    // 其他文件类型，提示下载完成
                    var dialog = new ContentDialog
                    {
                        Title = "下载完成",
                        Content = $"文件已保存到: {tempFilePath}",
                        CloseButtonText = "确定"
                    };
                    await dialog.ShowAsync();
                }
            }
            catch (Exception ex)
            {
                // 预览失败提示
                var dialog = new ContentDialog
                {
                    Title = "预览失败",
                    Content = ex.Message,
                    CloseButtonText = "确定"
                };
                await dialog.ShowAsync();
            }
        }

        /// <summary>
        /// 检查是否为视频文件
        /// </summary>
        private bool IsVideoFile(string extension)
        {
            var videoExtensions = new[] { ".mp4", ".avi", ".mkv", ".wmv", ".mov" };
            return videoExtensions.Contains(extension);
        }

        /// <summary>
        /// 检查是否为音频文件
        /// </summary>
        private bool IsAudioFile(string extension)
        {
            var audioExtensions = new[] { ".mp3", ".wav", ".flac", ".aac", ".wma" };
            return audioExtensions.Contains(extension);
        }

        /// <summary>
        /// 下载按钮点击事件
        /// </summary>
        private void DownloadButton_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            if (button != null && _selectedService != null)
            {
                var fileItem = button.Tag as FileShareItem;
                if (fileItem != null)
                {
                    DownloadFile(fileItem);
                }
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        private async void DownloadFile(FileShareItem fileItem)
        {


        /// <summary>
        /// 下载文件
        /// </summary>
        private async void DownloadFile(FileItem fileItem)
        {
            // 创建下载文件夹
            var downloadsFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
            Directory.CreateDirectory(downloadsFolder);

            var savePath = Path.Combine(downloadsFolder, fileItem.Name);

            // 创建进度报告
            var progress = new Progress<double>(percentage =>
            {
                // 可以添加进度条更新逻辑
            });

            try
            {
                // 下载文件
                await _fileShareHelper.DownloadFileAsync(_selectedService, fileItem.Path, savePath, progress);

                // 下载完成提示
                var dialog = new ContentDialog
                {
                    Title = "下载完成",
                    Content = $"文件已保存到: {savePath}",
                    CloseButtonText = "确定"
                };
                await dialog.ShowAsync();
            }
            catch (Exception ex)
            {
                // 下载失败提示
                var dialog = new ContentDialog
                {
                    Title = "下载失败",
                    Content = ex.Message,
                    CloseButtonText = "确定"
                };
                await dialog.ShowAsync();
            }
        }
    }
}